package com.cy.server.controller;

import com.cy.server.pojo.Admin;
import com.cy.server.pojo.RespBean;
import com.cy.server.service.IAdminService;
import com.cy.server.utils.FastDFSUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @peoject: yeb
 * @description: 个人中心
 * @author: LiShaoZhuo
 * @create: 2021-05-10 16:49
 **/
@RestController
public class AdminInfoController {

    @Autowired
    IAdminService adminService;

    @ApiOperation("更新当前用户信息")
    @PostMapping("/admin/info")
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)){
            SecurityContextHolder.getContext()
                    .setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation("更新用户密码")
    @PostMapping("/admin/updatePassword")
    public RespBean updateAdminPassword(@RequestBody Map<String,Object> adminInfo){
        String oldPass = (String) adminInfo.get("oldPass");
        String pass = (String) adminInfo.get("pass");
        Integer adminId = (Integer) adminInfo.get("adminId");
        return adminService.updateAdminPassword(oldPass,pass,adminId);
    }

    @ApiOperation("更新用户头像")
    @PostMapping("/admin/userface")
    public RespBean updateAdminUserFace(MultipartFile file, Integer id, Authentication authentication){
        String[] filePath = FastDFSUtils.upload(file);
        String url = FastDFSUtils.getTrackerUrl() + filePath[0] + "/" + filePath[1];
        return adminService.updateAdminUserface(url,id,authentication);
    }
}
